using System.Collections.Generic;
using System.Linq;
using FishFillets.Model;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using FishFillets.GameComponents.Helpers;

namespace FishFillets.GameComponents
{
    public class MapComponent : DrawableGameComponent
    {
        private readonly ContentManager manager;
        private readonly AssetHelper manager2;
        private SpriteBatch spriteBatch;

        private Texture2D gameMap;
        private readonly List<LevelRefComponent> LevelRefs;

        private readonly Map map;

        public MapComponent(Game game, Map map) 
            : base(game)
        {
            manager = new ContentManager(game.Services) { RootDirectory = "Content" };
            manager2 = new AssetHelper(Game.GraphicsDevice, manager.RootDirectory);
            this.map = map;
            LevelRefs = new List<LevelRefComponent>();
        }

        public override void Initialize()
        {
            foreach (LevelRef levelRef in map.Levels)
            {
                LevelRef parent = map.Levels.FirstOrDefault(l => l.Name == levelRef.Parent);
                LevelRefComponent level = new LevelRefComponent(Game, manager, manager2, levelRef, parent);
                LevelRefs.Add(level);
                level.Initialize();
            }

            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(Game.GraphicsDevice);
            foreach (LevelRefComponent component in LevelRefs)
            {
                component.SpriteBatch = spriteBatch;
            }
            gameMap = manager2.LoadTextureStream("images/menu/map_lower");
        }

        protected override void UnloadContent()
        {
            manager.Unload();
            manager2.UnloadAll();
        }

        public override void Draw(GameTime gameTime)
        {
            spriteBatch.Begin();
            spriteBatch.Draw(gameMap, new Rectangle(0, 0, gameMap.Width, gameMap.Height), Color.White);
            foreach (LevelRefComponent level in LevelRefs)
            {
                level.Draw(gameTime);
            }
            spriteBatch.End();
        }
    }
}
